﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using ERP.ERPModels.Production.MasterData;
using ERP.MasterData.Dtos;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.MasterData
{
    /// <summary>
    /// 车间服务实现
    /// </summary>
    public class WorkshopService : ApplicationService, IWorkshopService
    {
        private readonly IRepository<Workshop, int> _workshopRepository;
        private readonly ILogger<WorkshopService> _logger;

        public WorkshopService(
            IRepository<Workshop, int> workshopRepository,
            ILogger<WorkshopService> logger)
        {
            _workshopRepository = workshopRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取车间列表
        /// </summary>
        public async Task<PagedResultDto<WorkshopDto>> GetListAsync(GetWorkshopInputDto input)
        {
            var query = await CreateFilteredQueryAsync(input);

            var totalCount = query.Count();

            query = ApplySorting(query, input);

            query = query.PageBy(input.SkipCount, input.MaxResultCount);

            var items = query.ToList();

            return new PagedResultDto<WorkshopDto>(
                totalCount,
                ObjectMapper.Map<List<Workshop>, List<WorkshopDto>>(items)
            );
        }

        /// <summary>
        /// 获取车间详情
        /// </summary>
        public async Task<WorkshopDto> GetAsync(int id)
        {
            var workshop = await _workshopRepository.GetAsync(id);
            return ObjectMapper.Map<Workshop, WorkshopDto>(workshop);
        }

        /// <summary>
        /// 创建车间
        /// </summary>
        public async Task<WorkshopDto> CreateAsync(CreateWorkshopDto input)
        {
            // 检查车间编码是否已存在
            var existingWorkshop = await _workshopRepository.FirstOrDefaultAsync(x => x.WorkshopCode == input.WorkshopCode);
            if (existingWorkshop != null)
            {
                throw new UserFriendlyException("车间编码已存在");
            }

            var workshop = ObjectMapper.Map<CreateWorkshopDto, Workshop>(input);

            await _workshopRepository.InsertAsync(workshop);
            await CurrentUnitOfWork.SaveChangesAsync();

            _logger.LogInformation("创建车间成功，车间编码: {WorkshopCode}", workshop.WorkshopCode);

            return ObjectMapper.Map<Workshop, WorkshopDto>(workshop);
        }

        /// <summary>
        /// 更新车间
        /// </summary>
        public async Task<WorkshopDto> UpdateAsync(int id, UpdateWorkshopDto input)
        {
            // 确保id与input.Id一致
            if (id != input.Id && input.Id != 0)
            {
                id = input.Id;
            }

            var workshop = await _workshopRepository.GetAsync(id);

            // 检查车间编码是否已存在（排除自身）
            var existingWorkshop = await _workshopRepository.FirstOrDefaultAsync(x => x.WorkshopCode == input.WorkshopCode && x.Id != id);
            if (existingWorkshop != null)
            {
                throw new UserFriendlyException("车间编码已存在");
            }

            ObjectMapper.Map(input, workshop);

            await _workshopRepository.UpdateAsync(workshop);
            await CurrentUnitOfWork.SaveChangesAsync();

            _logger.LogInformation("更新车间成功，车间编码: {WorkshopCode}", workshop.WorkshopCode);

            return ObjectMapper.Map<Workshop, WorkshopDto>(workshop);
        }

        /// <summary>
        /// 删除车间（支持单删和批删）
        /// </summary>
        public async Task DeleteAsync(List<int> ids)
        {
            if (ids == null || !ids.Any())
            {
                throw new UserFriendlyException("请选择要删除的车间");
            }

            foreach (var id in ids)
            {
                await _workshopRepository.DeleteAsync(id);
            }

            await CurrentUnitOfWork.SaveChangesAsync();

            _logger.LogInformation("删除车间成功，数量: {Count}", ids.Count);
        }

        /// <summary>
        /// 生成车间编码
        /// </summary>
        public Task<string> GenerateWorkshopCodeAsync()
        {
            // 生成车间编码：WS + 年月日时分秒毫秒
            string code = "WS" + DateTime.Now.ToString("yyyyMMddHHmmss");
            return Task.FromResult(code);
        }

        /// <summary>
        /// 创建过滤查询
        /// </summary>
        private async Task<IQueryable<Workshop>> CreateFilteredQueryAsync(GetWorkshopInputDto input)
        {
            var query = await _workshopRepository.GetQueryableAsync();

            // 关键字搜索
            if (!string.IsNullOrWhiteSpace(input.Keyword))
            {
                query = query.Where(x =>
                    x.WorkshopCode.Contains(input.Keyword) ||
                    x.WorkshopName.Contains(input.Keyword));
            }

            // 车间编码
            if (!string.IsNullOrWhiteSpace(input.WorkshopCode))
            {
                query = query.Where(x => x.WorkshopCode.Contains(input.WorkshopCode));
            }

            // 车间名称
            if (!string.IsNullOrWhiteSpace(input.WorkshopName))
            {
                query = query.Where(x => x.WorkshopName.Contains(input.WorkshopName));
            }

            // 是否启用
            if (input.IsActive.HasValue)
            {
                query = query.Where(x => x.IsActive == input.IsActive.Value);
            }

            return query;
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private IQueryable<Workshop> ApplySorting(IQueryable<Workshop> query, GetWorkshopInputDto input)
        {
            // 如果没有指定排序，默认按照车间编码升序排序
            if (string.IsNullOrWhiteSpace(input.Sorting))
            {
                return query.OrderBy(x => x.WorkshopCode);
            }

            return query.OrderBy(input.Sorting);
        }
    }
}
